import sqlite3
import os

# Locate database file
db_path = 'aichat.db'
if not os.path.exists(db_path):
    if os.path.exists('data/aichat.db'):
        db_path = 'data/aichat.db'
    elif os.path.exists('backend/aichat.db'):
        db_path = 'backend/aichat.db'
    else:
        print("未找到数据库文件 aichat.db")
        raise SystemExit(1)

print(f"连接到数据库: {db_path}")

conn = sqlite3.connect(db_path)
cursor = conn.cursor()

print("\n检查数据库表结构...")
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = {table[0] for table in cursor.fetchall()}
print(f"找到的表: {tables}")

if 'messages' not in tables:
    print("错误: 未找到 messages 表")
    conn.close()
    raise SystemExit(1)

# 统计当前的消息数量
print("\n统计当前聊天记录...")
cursor.execute('SELECT COUNT(*) FROM messages')
total_count = cursor.fetchone()[0]
print(f"当前数据库中的消息总数: {total_count}")

# 统计会话数量
cursor.execute('SELECT COUNT(DISTINCT session_id) FROM messages')
session_count = cursor.fetchone()[0]
print(f"当前数据库中的会话总数: {session_count}")

# 显示会话ID列表
print("\n当前会话ID列表:")
cursor.execute('SELECT DISTINCT session_id FROM messages ORDER BY session_id')
sessions = cursor.fetchall()
for index, (session_id,) in enumerate(sessions, 1):
    cursor.execute('SELECT COUNT(*) FROM messages WHERE session_id = ?', (session_id,))
    msg_count = cursor.fetchone()[0]
    print(f"{index}. {session_id} ({msg_count}条消息)")

print("\n自动确认删除所有聊天记录...")
try:
    cursor.execute('DELETE FROM messages')
    conn.commit()
    print(f"成功删除所有 {total_count} 条消息")
except Exception as exc:
    print(f"删除过程中发生错误: {exc}")
    conn.rollback()
finally:
    conn.close()
    print("\n数据库连接已关闭")
